using Microsoft.EntityFrameworkCore;
using UniversalAdminSystem.Domian.UserManagement.Aggregates;
using UniversalAdminSystem.Domian.UserManagement.IRepository;
using UniversalAdminSystem.Domian.UserManagement.Entities;
using UniversalAdminSystem.Infrastructure.Persistence.DbContexts;
using UniversalAdminSystem.Domian.UserManagement.ValueObj;
using UniversalAdminSystem.Domian.Core.ValueObjects;

namespace UniversalAdminSystem.Infrastructure.Persistence.Repositories;

public class UserRepository : BaseRepository<User>, IUserRepository
{
    public UserRepository(UniversalAdminSystemDbContext dbContext) : base(dbContext)
    {
    }

    public override async Task<User?> GetByGuidAsync(Guid guid)
    {
        var userId = UserId.Create(guid);
        var user = await _TDs.FirstOrDefaultAsync(u => u.UserId == userId);
        System.Console.WriteLine($"user:{user.Account}");
        return user;
    }

    /// <summary>
    /// 用户软删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    /// <exception cref="NullReferenceException"></exception>
    public async Task DeleteUserSoftAsync(Guid id)
    {
        var user = await GetByGuidAsync(id) ?? throw new NullReferenceException("用户不存在");
        user.UpdateUserStatus(UserStatus.Deleted);
        await Update(user);
    }

    /// <summary>
    /// 通过账号查询用户
    /// </summary>
    /// <param name="account"></param>
    /// <returns></returns>
    public async Task<User?> GetUserByAccountAsync(string account)
    {
        var user = await _TDs.FirstOrDefaultAsync(u => u.Account == account);
        return user;
    }

    /// <summary>
    /// 通过邮箱查询用户
    /// </summary>
    /// <param name="email"></param>
    /// <returns></returns>
    public async Task<User?> GetUserByEmailAsync(string email)
    {
        var user = await _TDs.FirstOrDefaultAsync(u => u.Email == email);
        return user;
    }

    /// <summary>
    /// 添加用户信息
    /// </summary>
    /// <param name="userInfo"></param>
    /// <returns></returns>
    public async Task AddUserInfoAsync(UserInfo userInfo)
    {
        await _DbContext.UserInfos.AddAsync(userInfo);
    }
}